﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdateService.Mgr.Handler
{
    using System.Linq;
    using System.IO;
    using AutoUpdate.Model.Packet;
    public class updateVersionHandler : Handler
    {
        public updateVersionHandler()
        {
            this.name = "updateVersion";
        }

        public override void doAction(Packet packet)
        {
            string versionFile = Environment.CurrentDirectory + "\\" + ConfigMgr.getInstance().config.versionPath + "\\version.ini";

            string value = File.ReadAllText(versionFile, Encoding.UTF8);

            List<AutoUpdate.Model.Model.fileTransfer.fs_version> versionList = null;

            if (!string.IsNullOrEmpty(value))
            {
                versionList = AutoUpdate.Utility.Helper.JsonHelper.getObject<List<AutoUpdate.Model.Model.fileTransfer.fs_version>>(value);
            }

            Console.WriteLine(packet.MessageContent);

            AutoUpdate.Model.Model.fileTransfer.fs_version newVersionModel = AutoUpdate.Utility.Helper.JsonHelper.getObject<AutoUpdate.Model.Model.fileTransfer.fs_version>(packet.MessageContent);

            AutoUpdate.Model.Model.fileTransfer.fs_version versionModel = versionList.FirstOrDefault(a => a.version == newVersionModel.version);

            //versionModel = newVersionModel;

            versionModel.files = newVersionModel.files;

            File.WriteAllText(versionFile, AutoUpdate.Utility.Helper.JsonHelper.getString(versionList), Encoding.UTF8);

            AutoUpdate.Model.Packet.ResponsePacket response = new ResponsePacket();

            packet.FillData(response);

            response.PacketType = PacketType.Response;

            response.MessageContent = Newtonsoft.Json.JsonConvert.SerializeObject(versionList);

            ClientMgr.getInstance().transferMessage(response);
        }
    }
}
